<template>
  <div class="h-100">
    <AxiomToolbar justify="end">
      <AxiomButton icon="refresh" @click="$emit('refresh-documents')" text>刷新</AxiomButton>
    </AxiomToolbar>
    <AxiomGroup justify="center" align="center" direction="vertical" class="h-100">
      <AxiomDocumentUploader
        title="上传文本文件"
        :http-request="handleUpload"
        :before-upload="beforeUpload"
        :tip="uploadTip"
      />
    </AxiomGroup>
  </div>
</template>

<script setup>
import { inject, ref } from 'vue';
import {
  AxiomToolbar,
  AxiomButton,
  AxiomGroup,
  AxiomDocumentUploader,
} from 'axiom-view';
import { documentApi } from '@/api/knowledge/document.js';

const props = defineProps({
  knowledgeBase: { type: Object, required: true }
});

const emit = defineEmits(['refresh-documents']);

const { notification } = inject('axiom-utils');

const uploadTip = '已支持 TXT、MARKDOWN、MDX、PDF、HTML、XLSX、XLS、DOCX、CSV、VTT、PROPERTIES、MD、HTM，每个文件不超过15MB。';

function beforeUpload(file) {
  const isLt15M = file.size / 1024 / 1024 < 15;
  if (!isLt15M) {
    notification.error({ title: '文件无效', message: `文件 "${file.name}" 大小超过 15MB!` });
  }
  return isLt15M;
}

async function handleUpload(options) {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append('file', file);

  const uploadToast = notification.info({
    title: '上传中',
    message: `正在上传文件: ${file.name}`,
    duration: 0,
  });

  try {
    await documentApi.uploadDocument(props.knowledgeBase.id, formData);
    notification.success({ title: '成功', message: `文件 "${file.name}" 上传成功。` });
    onSuccess();
  } catch (error) {
    notification.error({ title: '上传失败', message: `文件 "${file.name}" 上传失败: ${error.message}` });
    onError(error);
  } finally {
    uploadToast.close();
  }
}
</script>